package com.koala.security.handler;

import cn.hutool.json.JSONUtil;
import com.koala.entity.SysUserDetails;
import com.koala.result.Result;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author koala
 * @date 2022/11/16 2:10
 */
@Component
public class DefaultAuthenticationSuccessHandler implements ServerAuthenticationSuccessHandler {

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        return Mono.defer(() -> Mono.just(webFilterExchange.getExchange().getResponse()).flatMap(response -> {
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            // 生成JWT token
            Map<String, Object> map = new HashMap<>(10);
            SysUserDetails userDetails = (SysUserDetails) authentication.getPrincipal();
            map.put("username", userDetails.getUsername());
            map.put("roles", userDetails.getAuthorities());
            DataBuffer dataBuffer = dataBufferFactory.wrap(JSONUtil.toJsonStr(Result.success(map)).getBytes());
            return response.writeWith(Mono.just(dataBuffer));
        }));
    }
}

